package com.dmall.opening.up.api.endpoint;

import com.dmall.opening.up.core.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.server.ResponseStatusException;

import javax.annotation.Resource;

@RestController
public class OrderController {

    @Resource
    private OrderRepository orders;

    @PostMapping("orders")
    public Order create(@RequestBody Request<String, Object> request) {
        return orders.create(request);
    }

    @GetMapping("orders")
    public Page<Order> paging(WebRequest request) {
        return orders.paging(Criteria.of(request.getParameterMap()));
    }

    @GetMapping("orders/{id}")
    public Order id(@PathVariable("id") Long id) {
        return orders.findOne(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
    }

    @PutMapping("orders/{id}/cancel")
    public void cancel(@PathVariable("id") Long id) {
        orders.findOne(id).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND)).cancel();
    }
}
